#!/bin/bash

# 配置
WORKSPACE_NAME="UGSDK.xcworkspace"
ARCHIVE_DIR="build"
DEVICE_ARCHIVE="$ARCHIVE_DIR/ios_devices.xcarchive"
SIMULATOR_ARCHIVE="$ARCHIVE_DIR/ios_simulator.xcarchive"
CONFIGURATION="Release"

# 公共构建参数
COMMON_BUILD_ARGS=(
  -workspace "$WORKSPACE_NAME"
  -scheme "$1"
  -configuration "$CONFIGURATION"
  only_active_arch=no
  SKIP_INSTALL=NO
  BUILD_LIBRARIES_FOR_DISTRIBUTION=YES
  OTHER_SWIFT_FLAGS="-Xfrontend -module-interface-preserve-types-as-written"
)

# 日志函数
log() {
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1"
}

# 清理函数
clean() {
    log "Cleaning build directory..."
    rm -rf "$ARCHIVE_DIR"
}

# 检查依赖
check_dependencies() {
    if ! command -v pod &> /dev/null; then
        log "CocoaPods not found. Please install it first."
        exit 1
    fi
    if ! command -v xcodebuild &> /dev/null; then
        log "Xcode command line tools not found. Please install them first."
        exit 1
    fi
}

# 构建XCFramework
build_xcframework() {
    local scheme_name=$1
    local framework_name=${2:-$1}

    log "Building $scheme_name for iOS Device..."
    xcodebuild archive \
      "${COMMON_BUILD_ARGS[@]}" \
      -destination "generic/platform=iOS" \
      -sdk iphoneos \
      -archivePath "$DEVICE_ARCHIVE" || exit 1

    log "Building $scheme_name for iOS Simulator..."
    xcodebuild archive \
      "${COMMON_BUILD_ARGS[@]}" \
      -destination "generic/platform=iOS Simulator" \
      -sdk iphonesimulator \
      -archivePath "$SIMULATOR_ARCHIVE" || exit 1

    log "Creating XCFramework for $scheme_name..."
    xcodebuild -create-xcframework \
      -framework "$DEVICE_ARCHIVE/Products/Library/Frameworks/$scheme_name.framework" \
      -framework "$SIMULATOR_ARCHIVE/Products/Library/Frameworks/$scheme_name.framework" \
      -output "$ARCHIVE_DIR/$framework_name.xcframework" || exit 1

    log "Cleaning up intermediate archives..."
    rm -rf "$DEVICE_ARCHIVE" "$SIMULATOR_ARCHIVE"
}

# 主流程
main() {
    check_dependencies
    clean

    log "Installing CocoaPods dependencies..."
    pod install || { log "pod install failed. Exiting..."; exit 1; }

    if [ $# -eq 0 ]; then
        log "Usage: $0 <scheme_name> [output_framework_name]"
        exit 1
    fi

    build_xcframework "$@"

    log "Build completed successfully!"
}

main "$@"